<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="upload"
      :limit="1"
      :class="{'disabled': fileList.length>0}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="ShowPercent" :percentage="percent" style="width:180px" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDKQGp8BxSgcHfmcBSTDgrmKcdOs4zdz4s',
  SecretKey: 'YppXy82g4B1aste8MJzOWTTJsABuNZU7'
})
export default {
  name: 'ImageUpload',
  components: {},
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      percent: 0,
      ShowPercent: false,
      uploading: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      //  方式一
      // const index = this.fileList.findIndex(t => t.uid === file.uid)
      // this.fileList.splice(index, 1)
      // 方式二
      // this.fileList = this.fileList.filter(t => t.uid !== file.uid)
      // 方式三
      this.fileList = fileList
    },
    preview(file) {
      this.dialogImageUrl = file.url
      this.fileList.push(file)
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload({ size, type }) {
      // console.log(file)
      if (!['image/jpeg', 'image/gif', 'image/bmp', 'image/png'].includes(type)) {
        this.$message.error('图片格式错误')
        return false
      }
      if (size > 5 * 1024 * 1024) {
        this.$message.error('图片太大了')
        return false
      }
      return true
    },
    // 上传函数
    upload({ file }) {
      this.ShowPercent = true
      this.uploading = true
      cos.putObject({
        Bucket: 'myrzzt-1308732495', /* 桶名称 */
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
        Key: new Date().getTime() + file.name, /* 起一个随机名 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        this.uploading = false
        // this.ShowPercent = false
        console.log(err || data)
        if (!err) {
          // 直接对fileList里面已经被改造的对象进行值得覆盖,也是响应式,
          // 如果是添加新的属性,通过直接索引添加,没有被再次改造,不是响应式
          this.fileList[0].url = `http://${data.Location}`
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .disabled .el-upload--picture-card {
  display: none;
}
</style>
